#include "userapi.h"

UserApi::UserApi(QObject *parent)
    : QObject{parent}
{
    baseUrl = Config::baseUrl;

    manager = new QNetworkAccessManager(0);
    //    connect(manager,&QNetworkAccessManager::finished,this,&Api::replyFinished);
    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));//post请求设置为json，才能发送josn格式文件
    request.setRawHeader("Authorization",  qApp->property("token").value<QString>().toLocal8Bit());
}

QNetworkReply* UserApi::login(QString username,QString pwd,QString code,QString uuid){
    //创建一个Json对象,这个Json对象就是要发送的内容，展开成Json数据如上所示
    QJsonObject jsonObj;
    jsonObj.insert("username",username);
    jsonObj.insert("password",pwd);
    if(code != ""){
        jsonObj.insert("code",code);
        jsonObj.insert("uuid",uuid);
    }
    QJsonDocument jsonDoc = QJsonDocument(jsonObj);
    QByteArray postData = jsonDoc.toJson(QJsonDocument::Compact);

    request.setUrl(QUrl(baseUrl + "login"));
    //post
    QNetworkReply* reply = manager->post(request, postData);

    //同步请求
    QEventLoop eventLoop;
    connect(manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    eventLoop.exec();
    return reply;
}

QNetworkReply *UserApi::logout()
{
    request.setUrl(QUrl(baseUrl + "logout"));
    QNetworkReply* reply = manager->get(request);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    return reply;
}

QNetworkReply *UserApi::captchaImage()
{
    request.setUrl(QUrl(baseUrl + "captchaImage"));
    QNetworkReply* reply = manager->get(request);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    return reply;
}

QNetworkReply *UserApi::codeImg(QString url)
{
    request.setUrl(QUrl(url));
    QNetworkReply* reply = manager->get(request);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    return reply;
}

QNetworkReply *UserApi::getInfo()
{
    request.setUrl(QUrl(baseUrl + "getInfo"));
    QNetworkReply* reply = manager->get(request);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    return reply;
}

QNetworkReply *UserApi::profile()
{
    request.setUrl(QUrl(baseUrl + "system/user/profile"));
    QNetworkReply* reply = manager->get(request);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    return reply;
}

QNetworkReply *UserApi::getById(int id)
{
    QString url = baseUrl + "system/user/";
    if(id > 0){
        url += QString::number(id);
    }
    request.setUrl(QUrl(url));
    QNetworkReply* reply = manager->get(request);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    return reply;
}

QNetworkReply *UserApi::uploadAvatar(QString filePath)
{
    //设置程序编码格式为utf-8
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    //构造manager
    QNetworkAccessManager *manager = new QNetworkAccessManager();

    //构造multiPart ，用来组装图片数据
    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    QHttpPart imagePart;
    //经测试，设置此content-type，并不是必须。我测试的为jpg文件，则是image/jpeg，其他的格式文件查找http状态码，或者查找HTTP  content-type
    imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));

    filePath.lastIndexOf("/");
    QString filename = filePath.mid(filePath.lastIndexOf("/") + 1);
    //此ContentDispositionHeader参数极为重要，如果不对，则发送图片不成功，name可以随意起名字，但是filename则必须是你要上传的文件名。  name就是服务器接收的参数名
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QString("form-data; name=\"%1\"; filename=\"%2\"").arg("avatarfile").arg(filename));

    QFile *file = new QFile(filePath);
    file->open(QIODevice::ReadOnly);
    //依照下面方式将图片文件的内容附着于multiPart上，
    imagePart.setBodyDevice(file);
    file->setParent(multiPart);
    multiPart->append(imagePart);

    //此处设置上传的url

    QNetworkRequest request(QUrl(baseUrl + "system/user/profile/avatar"));
    request.setRawHeader("Authorization",  qApp->property("token").value<QString>().toLocal8Bit());

    //发送post
    QNetworkReply *reply = manager->post(request, multiPart);

    QEventLoop eventLoop;
    connect(manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    eventLoop.exec();
    return reply;
}

QNetworkReply *UserApi::updatePersonalInfo(User *user)
{
    request.setUrl(QUrl(baseUrl + "system/user/profile"));
    QJsonObject obj = user->toJsonObject();
    QJsonDocument doc(obj);
    QByteArray data = doc.toJson();
    QNetworkReply *reply = manager->put(request,data);
    QEventLoop loop;
    connect(reply,&QNetworkReply::finished,&loop,&QEventLoop::quit);
    loop.exec();
    return reply;
}

QNetworkReply *UserApi::updateUser(User *user)
{
    request.setUrl(QUrl(baseUrl + "system/user"));
    QJsonObject obj = user->toJsonObject();
    QJsonDocument doc(obj);
    QByteArray data = doc.toJson();
    QNetworkReply *reply = manager->put(request,data);
    QEventLoop loop;
    connect(reply,&QNetworkReply::finished,&loop,&QEventLoop::quit);
    loop.exec();
    return reply;
}

QNetworkReply *UserApi::updatePwd(QString oldPwd, QString newPwd)
{
    request.setUrl(QUrl(baseUrl + "system/user/profile/updatePwd?oldPassword="
                        + oldPwd + "&newPassword=" + newPwd));

    QByteArray data;
    QNetworkReply *reply = manager->put(request,data);
    QEventLoop loop;
    connect(reply,&QNetworkReply::finished,&loop,&QEventLoop::quit);
    loop.exec();
    return reply;
}

QNetworkReply *UserApi::getRouters()
{
    request.setUrl(QUrl(baseUrl + "getRouters"));

    QNetworkReply* reply = manager->get(request);

    //同步请求
    QEventLoop eventLoop;
    //    connect(manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

    return reply;
}

QNetworkReply *UserApi::addUser(User *user)
{
    request.setUrl(QUrl(baseUrl + "system/user"));
//    QJsonObject obj;
//    obj.insert("deptId",user->deptId);
//    if(!user->email.isEmpty()){
//        obj.insert("email",user->email);
//    }
//    obj.insert("nickName",user->nickName);
//    obj.insert("password",user->password);
//    if(!user->phonenumber.isEmpty()){
//        obj.insert("phonenumber",user->phonenumber);
//    }
//    QJsonArray arrPostIds;
//    for(int i = 0;i< user->postIds.size();i++){
//        arrPostIds.append(user->postIds.at(i));
//    }
//    obj.insert("postIds",arrPostIds);
//    if(!user->remark.isEmpty()){
//        obj.insert("remark",user->remark);
//    }
//    QJsonArray arrRoleIds;
//    for(int i = 0;i< user->roleIds.size();i++){
//        arrRoleIds.append(user->roleIds.at(i));
//    }
//    obj.insert("roleIds",arrRoleIds);
//    obj.insert("sex",user->sex);
//    obj.insert("status",user->status);
//    obj.insert("userName",user->userName);
    QJsonObject obj = user->toJsonObject();
    QJsonDocument doc(obj);
    QByteArray data = doc.toJson();
    QNetworkReply* reply = manager->post(request,data);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    return reply;
}


//void Api::replyFinished(QNetworkReply *reply)
//{
//    //1、获取响应状态码
//    v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
//    if (v.isValid()){
//        //        qDebug() << v.toInt();
//    }
//    //2、获取响应头
//    v = reply->header(QNetworkRequest::ContentTypeHeader);
//    if (v.isValid()){
//        //        qDebug() << v.toString();
//    }
//    //3、获取响应信息
//    QByteArray bytes = reply->readAll();
//    //    qDebug() << bytes.data();
//}